import express from 'express';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createServerRenderMiddleware } from './middlewares/server-render';
import { testConnection } from './database/connection';
import charactersRouter from './routes/characters';
import conversationsRouter from './routes/conversations';

import * as config from './config';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

function resolve(...args: string[]) {
  return path.resolve(__dirname, ...args);
}

const app = express();

// 添加JSON解析中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 测试数据库连接
testConnection();

// API路由
app.use('/api/characters', charactersRouter);
app.use('/api/conversations', conversationsRouter);

let vite;
if (!config.IS_PROD) {
  const { createServer } = await import('vite');
  vite = await createServer({
    server: { middlewareMode: true },
    appType: 'custom',
    base: config.PUBLIC_PATH,
  });
  app.use(vite.middlewares);
} else {
  const compression = (await import('compression')).default;
  const sirv = (await import('sirv')).default;

  app.use(compression());
  app.use(config.PUBLIC_PATH, sirv('./dist/client', { extensions: [] }));
}

const serverRenderMiddleware = createServerRenderMiddleware({
  vite,
  isProd: config.IS_PROD,
  publicPath: config.PUBLIC_PATH,
  entryServerPath: config.IS_PROD
    ? resolve('../dist/server/entry-server.js')
    : resolve('../src/entry-server.ts'),
  templatePath: config.IS_PROD
    ? resolve('../dist/client/index.html')
    : resolve('../index.html'),
});

app.get('*all', serverRenderMiddleware);

app.listen(config.PORT, () => {
  console.log(`Express server listen in ${config.PORT}`);
});
